package com.zhouxiaoxuan13.consumer.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * RestTemplate和WebClient配置类
 * 配置Spring Cloud LoadBalancer负载均衡
 */
@Configuration
@LoadBalancerClient(
    // 指定要进行负载均衡的服务名称（必须与Consul中注册的服务名一致）
    value = "promotion-service", 
    configuration = RestTemplateConfig.class
)
public class RestTemplateConfig {

    /**
     * 配置RestTemplate支持负载均衡
     * @LoadBalanced注解使RestTemplate具备负载均衡能力
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * 配置WebClient支持负载均衡
     * WebClient是Spring WebFlux提供的响应式HTTP客户端
     */
    @Bean
    @LoadBalanced
    public WebClient.Builder webClientBuilder() {
        return WebClient.builder();
    }

    /**
     * 配置负载均衡策略 - 轮询算法（默认）
     * 如果不配置此Bean，默认使用RoundRobinLoadBalancer
     */
    /*
    @Bean
    ReactorLoadBalancer<ServiceInstance> roundRobinLoadBalancer(
            Environment environment, 
            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RoundRobinLoadBalancer(
            loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), 
            name
        );
    }
    */

    /**
     * 配置负载均衡策略 - 随机算法
     * 取消注释此方法可以切换到随机负载均衡策略
     */
    @Bean
    ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(
            Environment environment,
            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(
            loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class),
            name
        );
    }
}
